package work5.StudentInfManagement;

import com.sun.org.apache.bcel.internal.generic.SWITCH;
import work5.SqlConnection;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class StudentDao {
    private static Statement stmt = null;
    private static ResultSet rs = null;
    private static Connection conn = SqlConnection.getConn();

    public static void insert(Student s) {

        String sql = "insert into studentinf(id,name,major)" +
                "values (?,?,?)";
        try {
            PreparedStatement p = conn.prepareStatement(sql);
            p.setInt(1, s.getId());
            p.setString(2, s.getName());
            p.setString(3, s.getMajor());
            p.executeUpdate();

        } catch (SQLException e) {
            System.out.println("最后一条数据信息 输入有误，请重新输入");
        }
    }

    public static void delete(Student s) {
        String sql = "delete from studentinf where id=?";
        try {
            PreparedStatement p = conn.prepareStatement(sql);
            p.setInt(1, s.getId());
            p.executeUpdate();
        } catch (SQLException e) {
            System.out.println("最后一条数据信息 输入有误，请重新输入");
        }
    }

    public static void change(Student s) {

        //update tb_emp set name='张三' ,update_time=now() where id=1;
        String sql = "update studentinf set name=?,major=? where id=?";
        try {
            PreparedStatement p = conn.prepareStatement(sql);
            p.setString(1, s.getName());
            p.setString(2, s.getMajor());
            p.setInt(3, s.getId());
            p.executeUpdate();
        } catch (SQLException e) {
            System.out.println("最后一条数据信息 输入有误，请重新输入");
        }

    }

    public static List<Student> find(Student s) {//-1通过名字查找
        // 创建 Statement 对象
        try {
            stmt = conn.createStatement();
        } catch (SQLException e) {
            System.out.println("无法创建 Statement 对象");
            e.printStackTrace();
        }
        String sql;
        if (s.getId() == 0) {
            sql = "select * from studentinf ;";
        } else if (s.getId() == -1) {
            sql = "select * from studentinf where name=" + s.getName() + ";";
        } else {
            sql = "select * from studentinf where id=" + s.getId() + ";";
        }
        List<Student> results = new ArrayList<>();
        try {
            rs = stmt.executeQuery(sql);
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String major = rs.getString("major");
                results.add(new Student(id, name, major));
            }
        } catch (SQLException e) {
            System.out.println("输入有误请重新输入");
        }
        try {
            stmt.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return results;
    }


}
